import React, { Component } from 'react'
import "./less/Home.less"
import { Link } from 'react-router-dom'
import books from '../assets/home/books.png'
import examination from '../assets/home/examination.png'
import practice from '../assets/home/practice.png'
import subject from '../assets/home/subject.png'
import LinearProgress from '@material-ui/core/LinearProgress';
import { withStyles } from '@material-ui/core/styles';
import { HomeApi } from "../request/api"
import { connect } from 'react-redux'
import { LodingDispatch } from '../utils'
import { withRouter } from 'react-router'

const BorderLinearProgress = withStyles((theme) => ({
    root: {
        height: 10,
        borderRadius: 5,
    },
    colorPrimary: {
        backgroundColor: theme.palette.grey[theme.palette.type === 'light' ? 200 : 700],
    },
    bar: {
        borderRadius: 5,
        backgroundColor: '#2E57FF',
    },
}))(LinearProgress);

class Home extends Component {
    state = {
        collect: 0,
        exam: {
            itemCount: 0,
            title: "",
            actionCode: ""
        },
        exemItems: [],
        study: 0,
        wrong: 0,
    }

    // `/toggle/${this.state.exam.actionCode}`
    render() {
        return (
            <div className="home_page">
                <header>
                    <h2 onClick={this.clickHtwoFn.bind(this)}>{this.state.exam.title}</h2>
                    <Link to={{
                        pathname: `/toggle/${this.state.exam.actionCode}`, query: {
                            actionCode: this.state.exam.actionCode,
                            title:this.state.exam.title
                    }}}>切换考试科目 <i className="iconfont icon-xiangyou"></i></Link>
                </header>
                <div className="banner">
                    <div className="logoutbtn" onClick={this.logoutFn.bind(this)}>退出登录</div>
                    <div className="user">
                        <div className="welcome">欢迎精神小火来到狼队学习库！</div>
                    </div>
                    <div className="ti">
                        <div>已学{this.state.study}题</div>
                        <div>共{this.state.exam.itemCount}题</div>
                    </div>
                    <div className="bottom">
                        <section>
                            <div className="num">{this.state.wrong}</div>
                            <div className="txt">错题</div>
                        </section>
                        <section>
                            <div className="num">{this.state.collect}</div>
                            <div className="txt">收藏</div>
                        </section>
                    </div>
                </div>
                <div className="ad">
                    <img src={examination} alt="" />
                    <img src={books} alt="" />
                    <img src={practice} alt="" />
                </div>
                <div className="mytitle">
                    <h2>学科题库</h2>
                    <span>坚持每一天，成长看得见</span>
                </div>
                <ul className="list">
                    {
                        this.state.exemItems.map(item => (
                            <li key={item.id}>
                                <img src={subject} alt="" />
                                <section>
                                    <h3>{item.title}</h3>
                                    <p>{item.itemCount}/{item.itemCount}题</p>
                                    <BorderLinearProgress variant="determinate" value={100} />
                                </section>
                                <div className="btn" onClick={this.goCategoryPage.bind(this,item.actionCode)}>练习</div>
                            </li>
                        ))
                    }
                </ul>
            </div>
        )
    }
    goCategoryPage(code) {
        // 跳到分类页
        this.props.history.push(`/category/${code}`)
    }
    clickHtwoFn() {
        this.props.showAlertFn("点我做撒","info")
    }
    // 退出登录
    logoutFn() {
        // 清除localStorage的登录信息
        localStorage.removeItem('x-auth-token')
        localStorage.removeItem('actionCode')
        this.props.showAlertFn("登出成功，即将跳转至登录页面","info")
        setTimeout(() => {
            let token = localStorage.getItem("x-auth-token");
            if (!token) {
                // 显示loading
                this.props.openLoadingFn();
                // 过1.5秒关闭
                setTimeout(() => {
                    this.props.closeLoadingFn();    // 关闭loading
    
                    // 存储字体大小
                    let fz = document.querySelector('html').style.fontSize;
                    sessionStorage.setItem('fz', fz);
    
                    // 没有token就跳到登录页
                    this.props.history.push("/login");
                }, 1500)
    
                return;
            }
    
        },800)
    }
    componentDidMount() {
        let token = localStorage.getItem("x-auth-token");

        if (!token) {
            // 显示loading
            this.props.openLoadingFn();
            // 过1.5秒关闭
            setTimeout(() => {
                this.props.closeLoadingFn();    // 关闭loading

                // 存储字体大小
                let fz = document.querySelector('html').style.fontSize;
                sessionStorage.setItem('fz', fz);

                // 没有token就跳到登录页
                this.props.history.push("/login");
            }, 1500)

            return;
        }

        HomeApi({
            actionCode: localStorage.getItem('actionCode')
        }).then(res => {
            if (res.errCode === 0) {
                let { collect, exam, exemItems, study, wrong } = res.data;
                this.setState({
                    collect, exam, exemItems, study, wrong
                })

                // console.log(collect, study, wrong)
            }
        })
    }
    UNSAFE_componentWillMount() {
        if (sessionStorage.getItem('fz')) {
            document.querySelector('html').style.fontSize = sessionStorage.getItem('fz');
        }
    }
}


export default connect(null, LodingDispatch)(withRouter(Home))